import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimSDKListener.dart';
import 'package:tencent_cloud_chat_sdk/enum/log_level_enum.dart';
import 'package:tencent_cloud_chat_sdk/manager/v2_tim_manager.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';
import 'package:tencent_cloud_chat_uikit/data_services/core/core_services.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/theme/tui_theme.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/screen_utils.dart';
import 'package:tencentcloud_ai_desk_customer/tencentcloud_ai_desk_customer.dart' as ai;
import 'package:tencentcloud_ai_desk_customer/theme/tui_theme.dart' as aiUI;
import 'package:yqmssa_app/config/app_config.dart';
import 'package:yqmssa_app/router/page_router.dart';
import 'package:yqmssa_app/utils/shared_utils.dart';
import 'package:yqmssa_app/utils/wx_utils.dart';
import 'package:yqmssa_app/views/index/request/message_request.dart';
import 'package:yqmssa_app/views/message/chat_method.dart';
import 'package:yqmssa_app/widget/default_dialog_widget.dart';

final tencentImUtils = TencentImUtils.instance;

class TencentImUtils {
  static TencentImUtils? _instance;

  static TencentImUtils get instance {
    _instance ??= TencentImUtils._internal();
    return _instance!;
  }

  late final CoreServicesImpl _coreInstance = TIMUIKitCore.getInstance();

  late V2TIMManager tencentImSDKPlugin = TIMUIKitCore.getSDKInstance();

  TencentImUtils._internal();

  Map<String, dynamic> chatMap = {};

  void init() {
    _coreInstance.setTheme(
        theme: const TUITheme(
      chatBgColor: Color(0XFFF3F3F3),
      primaryColor: Color(0XFFF4DCC1),
      chatMessageItemFromSelfBgColor: Color(0XFFF4DCC1),
      chatMessageItemFromOthersBgColor: Colors.white,
      chatTimeDividerTextColor: Color(0XFFF3F3F3),
      textColor: Colors.white,
      chatHeaderBgColor: Colors.white,
    ));
    _coreInstance
        .init(
            sdkAppID: 1400702447,
            loglevel: LogLevelEnum.V2TIM_LOG_ALL,
            language: LanguageEnum.zhHans,
            platform: DeviceType.Mobile,
            listener: V2TimSDKListener())
        .then((value) {
      imUserLogin();
    });
  }

  ImGetSigDataModel? get _imSignData {
    final data = sharedUtils.sharedPrefs.getString("imSign") ?? "";
    if (data.isNotEmpty) {
      return ImGetSigDataModel.fromJson(jsonDecode(data));
    }
    return null;
  }

  set _imSignData(ImGetSigDataModel? data) {
    if (data != null) {
      sharedUtils.sharedPrefs.setString("imSign", jsonEncode(data.toJson()));
    } else {
      sharedUtils.sharedPrefs.remove("imSign");
    }
  }

  ///获取签名
  void getSign([VoidCallback? call]) async {
    ChatMethods.login().then((value) {
      _imSignData = value;
      call?.call();
    }).catchError((err) {
      getSign();
    });
  }

  ///登录
  void imUserLogin() async {
    await _coreInstance.login(userID: _imSignData?.userId ?? "", userSig: _imSignData?.sig ?? "").then((onValue) {
      if (onValue.code == 6206) {
        getSign(imUserLogin);
      } else {
        ai.TencentCloudAIDeskCustomer.init(
          sdkAppID: 1400702447, // 腾讯云 IM 控制台创建应用的 SDKAppID
          userID: _imSignData?.userId ?? "", // 详情可参见腾讯云 IM 登录鉴权
          userSig: _imSignData?.sig ?? "", // 详情可参见腾讯云 IM 登录鉴权
          config: ai.TencentCloudCustomerConfig(
            useMessageReadReceipt: false,
          ), // 可选全局默认配置， 具体参数及使用方式可查看该类注释
        );
        ai.TencentCloudAIDeskCustomer.getIMUIKitInstance().setTheme(
            theme: const aiUI.TUITheme(
          chatBgColor: Color(0XFFF3F3F3),
          primaryColor: Color(0XFFFF6800),
          chatMessageItemFromSelfBgColor: Color(0XFFFF6800),
          chatMessageItemFromOthersBgColor: Colors.white,
          chatTimeDividerTextColor: Color(0XFFF3F3F3),
          textColor: Colors.white,
          adminColor: Color(0XFFFF6800),
          conversationItemBgColor: Colors.red,
          chatHeaderBgColor: Colors.white,
          appbarBgColor: Color(0XFFFF6800),
        ));
      }
    });
  }

  ///清空所有本地和云端历史消息
  cleanMessageHistory(String id) async {
    //清空单聊本地及云端的消息（不删除会话）
    await TencentImSDKPlugin.v2TIMManager.getMessageManager().clearC2CHistoryMessage(userID: id); // 需要清空记录的用户id
  }

  ///删除会话
  deleteConversation(String serviceId) async {
    //删除会话
    await TencentImSDKPlugin.v2TIMManager.getConversationManager().deleteConversation(
          conversationID: "c2c_$serviceId", //需要删除的会话id
        );
  }

  ///跳转页面
  pushPage([bool isBack = true]) {
    if (AppConfig.appInitData.isXcx == 1) {
      if (AppConfig.appInitData.jumpXcx == 1) {
        AppConfig.launchLink(sharedUtils.service?.customerAcquisition ?? "");
        MessageRequest.updateIsDistinguish();
      } else {
        WechatUtils.pushWxXcx(sharedUtils.service?.id ?? 0);
      }
    }
    if (AppConfig.appInitData.isChat == 1) {
      Future.delayed(Duration(seconds: AppConfig.appInitData.isXcx < 1 ? 0 : 2), () {
        if (AppConfig.appInitData.chatBot == 1) {
          if (isBack) {
            Get.toNamed(PageRouter.intelligenceCustomer);
          } else {
            Get.offNamed(PageRouter.intelligenceCustomer);
          }
        } else {
          ChatMethods.sendMessage(sharedUtils.service?.serviceTencentId ?? "");
          if (isBack) {
            Get.toNamed(PageRouter.humanCustomer);
          } else {
            Get.offNamed(PageRouter.humanCustomer);
          }
        }
      });
    }
  }

  ///拨打电话
  void tellPhone() async {
    if (!sharedUtils.phone) {
      final res = await Get.dialog(const DefaultDialogWidget(title: "${AppConfig.appName}想要打开电话", content: "为了实现快捷拨号功能，需要您同意访问电话进行号码拨打"));
      if (res == null || !res) return;
      if (res != null && res) sharedUtils.phone = true;
    }
    final data = sharedUtils.service;
    AppConfig.launchPhone(data?.mobile ?? "");
  }

  ///添加微信
  void addWeChat() async {
    if (!sharedUtils.wei) {
      final res = await Get.dialog(const DefaultDialogWidget(title: "${AppConfig.appName}想要打开微信", content: "为了实现快捷添加微信功能，需要您同意访问微信进行添加"));
      if (res == null || !res) return;
      if (res != null && res) sharedUtils.wei = true;
    }
    final data = sharedUtils.service;
    if (AppConfig.appInitData.jumpXcx == 1) {
      AppConfig.launchLink(data?.customerAcquisition ?? "");
      MessageRequest.updateIsDistinguish();
      return;
    }
    WechatUtils.pushWxXcx(data?.id ?? 0);
  }

  ///退出登录
  void logout() async {
    await ai.TencentCloudAIDeskCustomer.dispose();
    await _coreInstance.logout();
  }

  void inviteDialog() {
    Get.dialog(Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        InkWell(
          onTap: () {
            Get.back();
            addWeChat();
          },
          child: Image.network(
            AppConfig.appInitData.channelText?.chatPicture ?? "",
            width: 260,
            errorBuilder: (context, obj, st) {
              return Image.asset(
                AppConfig.imagePath("invite_dialog.png"),
                width: 260,
              );
            },
          ),
        ),
        const SizedBox(height: 24),
        IconButton(
          onPressed: Get.back,
          icon: const Icon(Icons.highlight_remove, color: Colors.white, size: 36),
        ),
      ],
    ));
  }
}
